<template>
  <div v-loading="loading" class="upload-container">
    <el-upload
      ref="refUpload"
      class="upload"
      action="action"
      :auto-upload="false"
      :http-request="uploadBanner"
      :before-upload="beforeUpload"
      :on-change="handleChange"
      :limit="1"
    >
      <el-button type="primary" class="el-icon-upload">选择图片</el-button>
      <template v-slot:tip>
        <div class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
      </template>
    </el-upload>
    <el-row :gutter="5" style="margin-top: 15px">
      <el-col :span="8" style="line-height: 40px; font-size: 14px"> 是否现在启用: </el-col>
      <el-col :span="6">
        <el-select v-model="is_use" placeholder="请选择" style="width: 200px">
          <el-option
            v-for="item in options.isUseOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-col>
    </el-row>
    <div class="upload-footer">
      <el-button @click="cancel"> 取消 </el-button>
      <el-button type="primary" @click="submitData"> 提交 </el-button>
    </div>
  </div>
</template>

<script setup>
import { addBanner, editBanner } from '@/api/banner'
import options from '@/constants/index'
import { ElMessage } from 'element-plus'
import { ref } from 'vue'

const loading = ref(false)
const refUpload = ref(null)
const ishaveData = ref(false)
const formData = ref(null)
const emit = defineEmits(['closeDrawer', 'updateBannerData'])
const props = defineProps({
  drawerStatus: {
    type: String,
    default: ''
  },
  editId: {
    type: String,
    default: ''
  }
})
defineOptions({ name: 'DrawerSlot' })
const is_use = defineModel('is_use', { type: Boolean, default: false })

// 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
const handleChange = function (file) {
  if (file.size) {
    ishaveData.value = true
  } else {
    ishaveData.value = false
  }
}
// 上传文件之前钩子
const beforeUpload = function (file) {
  const type = file.name.substring(file.name.lastIndexOf('.') + 1)
  const typeInfo = ['jpg', 'png', 'jpeg']
  if (!typeInfo.includes(type)) {
    ElMessage({
      type: 'error',
      message: '只支持jpg,png,jpeg文件格式！'
    })
    ishaveData.value = false
    return false
  }
  if (file.size / 1024 > 500) {
    ElMessage({
      type: 'error',
      message: '图片不能大于500kb！'
    })
    ishaveData.value = false
    return false
  }
  const postFormData = new FormData()
  postFormData.append('files', file)
  postFormData.append('is_use', is_use.value)
  formData.value = postFormData
}
// 新增或者编辑提交
const submitData = function () {
  if (ishaveData.value === false) {
    ElMessage({
      type: 'error',
      message: '请选择图片'
    })
    return
  }
  refUpload.value.submit()
}
// 新增或编辑图片请求
const uploadBanner = async function () {
  loading.value = true
  const postformData = formData.value
  // 编辑逻辑
  if (props.drawerStatus === 'update') {
    try {
      await editBanner(props.editId, postformData)
      ElMessage({
        type: 'success',
        message: '编辑轮播图成功'
      })
      loading.value = false
      ishaveData.value = false
      refUpload.value.clearFiles()
      // 重新拉数据
      emit('updateBannerData')
    } catch (error) {
      console.log('error: ', error)
      loading.value = false
    }
  } else {
    // 新增逻辑
    try {
      await addBanner(postformData)
      ElMessage({
        type: 'success',
        message: '添加轮播图成功'
      })
      loading.value = false
      ishaveData.value = false
      refUpload.value.clearFiles()
      // 重新拉数据
      emit('updateBannerData')
    } catch (error) {
      console.log('error: ', error)
      loading.value = false
    }
  }
}
// 取消
const cancel = function () {
  emit('closeDrawer')
  refUpload.value.clearFiles()
}
</script>

<style lang="scss" scoped>
.upload-container {
  padding: 20px;
  padding-left: 50px;
}

.upload-footer {
  margin-top: 20px;
}
</style>
